/**
 * 分享相关功能
 */
import { mysql } from 'src-ssr/db/connect';
import TableHelper from 'src-ssr/db/tableHelper';
import * as tools from 'src-ssr/util/common';
import { Sequelize, Op, QueryTypes } from 'sequelize';
import models, { sequelize } from 'src-ssr/db/sequelize';
import moment from 'moment';

// 配送明细数据
export const deliveryDetail = async (req, res) => {
  const { id } = req.body;

  const where = {
    share_uid: id
  };

  let master = null;
  try {
    master = await models.t_deliveries.findOne({
      attributes: ['uid', 'tenant_id', 'bill_no', 'remark', 'logistics', 'logistics_no', 'consignee', 'tel', 'address', 'reading_times'],
      include: [{
        model: models.t_delivery_details,
        attributes: ['deliver_amount', 'remark'],
        include: [{
          model: models.t_sale_details,
          attributes: [['amount', 'sale_amount'], ['remark', 'sale_detail_remark']],
          include: [{
            model: models.t_materials,
            attributes: ['material_name', 'material_model', 'material_name_model', 'material_unit', ['default_image', 'material_image']]
          }, {
            model: models.t_sales,
            attributes: [['bill_no', 'sale_bill_no'], 'type', 'consignee', 'tel', 'address'],
            include: [{
              model: models.t_customers,
              attributes: [['nickname', 'customer_name']]
            }, {
              model: models.m_consumers,
              attributes: [['nickname', 'consumer_name']]
            }]
          }]
        }]
      }],
      where
    });

    models.t_deliveries.update({ reading_times: Sequelize.literal('IFNULL(reading_times, 0) + 1') }, { where }); // 更新阅读次数
  } catch (e) {
    console.error('取配送单数据出错', e);
  }

  if (master) {
    // 租户信息
    const tenant = await models.m_tenants.findOne({
      attributes: ['tenant_name', 'company', 'province', 'city', 'district', 'street', 'address', 'link_man', 'link_phone'],
      where: { id: master.tenant_id },
      raw: true
    });
    // console.log(master)
    // 处理数据
    master = master.toJSON();
    master.uid = tools.binToUuid(master.uid);
    master.reading_times = master.reading_times || 0;

    master.tenant_name = tenant.tenant_name;
    master.tenant_company = tenant.company;
    master.tenant_address = `${tenant.province}${tenant.city}${tenant.district}${tenant.street}${tenant.address}`;
    master.tenant_tel = tenant.link_phone;

    for (const detail of master.t_delivery_details) {
      tools.flatDetail(['t_sale_detail', 't_material', 't_sale', 't_customer', 'm_consumer'], detail); // 拉平信息

      // 数量转数值
      for (const key of ['deliver_amount']) {
        if (detail[key]) detail[key] = Number(detail[key]);
      }
    }
  } else {
    master = null;
  }

  res.json(master);
};
